package saas.adapter.sdk.init;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.InitializingBean;
import saas.adapter.sdk.entity.TenantConversionRelation;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @title: TenantConversionRelationInitializer
 * @description: saas租户映射配置初始化器
 * @author: guan.xin
 * @create: 2021-11-15 18:50
 * @since: JDK8
 */

@Slf4j
public class TenantConversionRelationInitializer implements InitializingBean {

    private static final Map<String, TenantConversionRelation> STORE_CODE_TO_TENANT_CONVERSION_RELATION = new HashMap<>();

    private static final Map<String, TenantConversionRelation> MP_SAAS_TENANT_CODE_TO_TENANT_CONVERSION_RELATION = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        // 定时从远程(baseinfo)拉取oms租户映射信息
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("pull-oms-tenant-mapping-config-pool-%d").daemon(true).build());

        scheduledExecutorService.scheduleWithFixedDelay(this::getTenantConversionRelationInfo, 0, 1, TimeUnit.HOURS);
    }

    public static TenantConversionRelation getTenantConversionRelationByStoreCode(String storeCode) {
        return STORE_CODE_TO_TENANT_CONVERSION_RELATION.get(storeCode);
    }

    public static TenantConversionRelation getTenantConversionRelationByMpTenantCode(String mpTenantCode) {
        return MP_SAAS_TENANT_CODE_TO_TENANT_CONVERSION_RELATION.get(mpTenantCode);
    }

    /**
     * 远程获取saas租户映射关系配置定时器（从oms BaseInfo获取相关配置信息）
     */
    private void getTenantConversionRelationInfo() {
        TenantConversionRelation tenantConversionRelation = new TenantConversionRelation()
                .setStoreCode("JD_PUMA")
                .setMpTenantCode("MP0001")
                .setOmsTenantCode("OMS0001");

        STORE_CODE_TO_TENANT_CONVERSION_RELATION.put(tenantConversionRelation.getStoreCode(), tenantConversionRelation);

        MP_SAAS_TENANT_CODE_TO_TENANT_CONVERSION_RELATION.put(tenantConversionRelation.getMpTenantCode(), tenantConversionRelation);
    }
}
